package com.software.levelupserver.service.impl;

import com.software.levelupserver.entity.Badge;
import com.software.levelupserver.entity.SecurityUserDetails;
import com.software.levelupserver.entity.SystemTask;
import com.software.levelupserver.entity.User;
import com.software.levelupserver.mappers.BadgeMapper;
import com.software.levelupserver.mappers.SystemTaskMapper;
import com.software.levelupserver.service.SystemTaskService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class SystemTaskServiceImpl implements SystemTaskService {
    @Resource
    private SystemTaskMapper systemTaskMapper;
    @Resource
    private BadgeMapper badgeMapper;

    /**
     * 能够获取安全认证之后的用户信息
     * @return
     */
    public User getAuthentication(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null){
            System.out.println(authentication.getPrincipal());
            return (User) authentication.getPrincipal();
        }else {
            return null;
        }
    }

    /**
     * 用户领取系统任务
     * @param systemTaskId
     * @param time
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public int addUserSystemTask(int systemTaskId, String time, String startDate, String endDate) {
        User user = getAuthentication();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        LocalDate start = LocalDate.parse(startDate, dateTimeFormatter);
        LocalDate end = LocalDate.parse(endDate, dateTimeFormatter);

        List<String> times = new ArrayList<>();
        int days = 0;

        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)){
            times.add(dateTimeFormatter.format(date) + " " + time);
            ++days;
        }

        int result = 0;
        for (String taskTime : times){
            if (user != null)
                result += systemTaskMapper.insertUserSystemTask(user.getUserId(), systemTaskId, 0, taskTime);
        }
        if (result == days){
            return result;
        }else {
            return 0;
        }
    }

    /**
     * 1.更新系统任务状态 <br/>
     * 2.判断是否更新任务到完成状态 <br/>
     * 3.如果是完成任务：获取用户完成该类型系统任务数量 <br/>
     * 4.判断数量是否到达可以获得下一等级徽章的条件 <br/>
     * 5.如果达到：在用户徽章表中新增用户获得的徽章 <br/>
     * @param systemTask
     * @return 更新任务状态成功返回值是一个Badge实例，更新任务失败返回值是null
     */
    @Override
    public Badge updateUserSystemTask(SystemTask systemTask) {
        User user = getAuthentication();
        Badge nextBadge = new Badge();

        boolean result = false;
        if (user != null)
            result = systemTaskMapper.updateUserSystemTask(user.getUserId(), systemTask);

        //TODO 返回的数据需要再次斟酌，保证前端可以判断用户是否获得了徽章

        //判断是否成功更新了任务状态
        if (result){
            //用户完成任务之后（即更新系统任务到完成状态），进行是否满足获取获取徽章条件的判断
            if (systemTask.getStatus() == 1){
                //查询用户完成的相应类型的系统任务
                int systemTaskNum = systemTaskMapper.countSystemTaskByType(user.getUserId(), systemTask.getType());
                //获取用户获得的该类型的最高等级的徽章
                Badge badge = badgeMapper.selectBadgeByTypeAndUserId(systemTask.getType(), user.getUserId());
                //获取该类型的所有等级徽章
                List<Badge> badgeList = badgeMapper.selectBadgeByType(systemTask.getType());

                //判断用户是否获得过该类型的徽章，如果没获得过（进行对获得徽章条件的判断，并进行徽章的新增）
                if (badge == null) {
                    Badge minBadge = badgeList.get(0);
                    if (minBadge != null) {
                        if (systemTaskNum >= minBadge.getFinishNum()){
                            //用户新增徽章
                            int isSuccess = badgeMapper.addBadge(user.getUserId(), minBadge.getBadgeId());
                            if (isSuccess > 0){
                                nextBadge = minBadge;
                                return nextBadge;
                            }
                        }
                    }
                }else {
                    //判断是否满足获取徽章的条件
                    if (systemTaskNum > badge.getFinishNum()){
                        Badge upBadge = badgeList.get(badge.getBadgeGrade());
                        if (upBadge != null){
                            if (systemTaskNum >= upBadge.getFinishNum()){
                                //用户新增徽章
                                int isSuccess = badgeMapper.addBadge(user.getUserId(), upBadge.getBadgeId());
                                if (isSuccess > 0){
                                    nextBadge = upBadge;
                                    return nextBadge;
                                }
                            }
                        }

                    }
                }

            }else {
                //不是更新系统任务到完成状态
                return nextBadge;
            }

        }else {
            //更新任务状态失败
            return null;
        }

        return nextBadge;
    }

    /**
     * 删除（取消）领取的任务
     * @param systemTask
     * @return
     */
    @Override
    public int deleteUserSystemTask(SystemTask systemTask) {
        User user = getAuthentication();

        int result = -1;
        if (user != null) {
            result = systemTaskMapper.deleteUserSystemTask(user.getUserId(), systemTask);
        }

        return result;
    }

    /**
     * 获取用户领取的系统任务
     * @return
     */
    @Override
    public List<SystemTask> getAllSystemTasks() {
        List<SystemTask> systemTaskList = systemTaskMapper.selectAllSystemTask();

        return systemTaskList;
    }

    /**
     * 根据userId查询系统任务
     * @return
     */
    @Override
    public List<SystemTask> getSystemTasksByUserId() {
        User user = getAuthentication();

        List<SystemTask> systemTaskList = null;
        if (user != null)
            systemTaskList = systemTaskMapper.selectSystemTasksByUserId(user.getUserId());

        return systemTaskList;
    }

    @Override
    public List<SystemTask> getSystemTasksByType(int type) {
        List<SystemTask> systemTaskList = systemTaskMapper.selectSystemTasksByType(type);
        return systemTaskList;
    }

    /*后台管理系统的SQL操作*/
    /**
     * 新增系统任务
     * @param systemTask
     * @return
     */
    @Override
    public int addSystemTask(SystemTask systemTask) {

        int result = systemTaskMapper.insertSystemTask(systemTask);

        return result;
    }
}
